//
//  AppDelegate.swift
//  letuofu
//
//  Created by WH-JS on 2019/10/15.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import CoreData
import MAMapKit
import SwiftyStoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, JPUSHRegisterDelegate {

    var window: UIWindow?
    var openWithPush = false
    
    func getCurrrentSysversion(callback: @escaping (Bool,[String:Any?]) -> Void) {
        let params :[String:Any] = ["type": 1]
        API.formRequest(url: APIUrl.YI_GetCurrrentSysversion, params: params, callback: { (result) in
            callback(result.success, result.data?.getDictionary("data") ?? [:])
        })
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        getCurrrentSysversion(callback: { (s,data) in
            let infoDictionary : [String : Any] = Bundle.main.infoDictionary!
            let minorVersion = anyToDouble(infoDictionary["CFBundleShortVersionString"]) ?? 0 // 版本号(内部标示)
            LocalStorage.saveDouble(anyToDouble(data["number"] ?? 0), forKey: NewVersionString)
            if s {
                if (anyToDouble(data["number"] ?? 0) ?? 0 < minorVersion) {
                    LocalStorage.saveBool(true, forKey: ISINREVIEW)
                } else {
                    LocalStorage.saveBool(false, forKey: ISINREVIEW)
                }
            } else {
                LocalStorage.saveBool(false, forKey: ISINREVIEW)
            }
            
        
        })
        //友盟
        UMCommonLogSwift.setUpUMCommonLogManager()
        UMCommonSwift.setLogEnabled(bFlag: true)
        UMCommonSwift.initWithAppkey(appKey: "5da95b000cafb2e25f000136", channel: "乐驼福利平台")
        configUSharePlatforms()
        initjPushApns()
        JPUSHService.setup(withOption: launchOptions, appKey: "926a4a80f35cce917ddb1176", channel: "App Store", apsForProduction: false, advertisingIdentifier: "")
        
        //        UMAnalyticsSwift.setScenarioType(eSType: eScenarioType.E_UM_GAME)
        //高德地图
        AMapServices.shared()?.apiKey = "0dbb8a7b733c9dec7d1826f404b8d5a8"
        AMapServices.shared()?.enableHTTPS = true
        
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window!.makeKeyAndVisible()
        
        //关闭夜晚模式
        if #available(iOS 13.0, *) {
            self.window?.overrideUserInterfaceStyle = .light
        }
        self.window?.backgroundColor = .white

        let infoDictionary : [String : Any] = Bundle.main.infoDictionary!
        let minorVersion = anyToString(infoDictionary["CFBundleShortVersionString"]) ?? ""
        if (!(LocalStorage.getBool(forKey: YINDAO_KEY+minorVersion) ?? false)) {
            let vc = L_StartVC()
            self.window!.rootViewController = vc
            LocalStorage.saveBool(true, forKey: YINDAO_KEY+minorVersion)
        } else {
            
            let nav = PushAndPopNavigationController()
            nav.isNavigationBarHidden = true
            let vc = L_LoginVC()
            nav.setViewControllers([vc], animated: false)
            self.window!.rootViewController = nav
        }

        
        //内购监听
        SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
            for purchase in purchases {
                switch purchase.transaction.transactionState {
                case .purchased, .restored:
                    if purchase.needsFinishTransaction {
                        // Deliver content from server, then:
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                    // Unlock content
                case .failed, .purchasing, .deferred:
                    break // do nothing
                @unknown default:
                    break
                }
            }
        }
        
        if #available(iOS 11, *) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        }
        
        //点击推送通知栏通知,进来之后 处理数据,
        if let userInfo = launchOptions?[.remoteNotification] as? [AnyHashable: Any] {
            print(userInfo)

            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
//                let vc = M_NewsListVC()
//                UIViewController.topMostController()?.pushViewController(vc)
            }
        }
        //初始化日志打印
        initLog()
        return true
    }
    
    
    func changeMall() {
        let nav = self.window!.rootViewController as! PushAndPopNavigationController
        nav.isNavigationBarHidden = true
        let main = nav.viewControllers[1] as! MainTabBarController
        nav.popToViewController(main, animated: true)
        main.selectedIndex = 0
//        MainTabBarController.getHomePageDynamic { (tabbarVC) in
//            if let vc = tabbarVC {
//                nav.setViewControllers([vc], animated: false)
//                self.window!.rootViewController = nav
//            }
//        }
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("did Fail To Register For Remote Notifications With Error:\(error)")
    }
    
    // iOS 12 Support

    func jpushNotificationCenter(_ center: UNUserNotificationCenter?, openSettingsFor notification: UNNotification?) {
        if notification != nil && (notification?.request.trigger is UNPushNotificationTrigger) {
            //从通知界面直接进入应用
        } else {
            //从通知设置界面进入应用
        }
    }
    // iOS 10 Support
    func jpushNotificationCenter(_ center: UNUserNotificationCenter?, didReceive response: UNNotificationResponse?, withCompletionHandler completionHandler: @escaping () -> Void) {
        // Required
        let userInfo = response?.notification.request.content.userInfo
        if userInfo != nil {
            openNews(userInfo: userInfo! as! [String:Any?])
        }
        
        if (response?.notification.request.trigger is UNPushNotificationTrigger) {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler() // 系统要求执行这个方法
    }

    func openNews(userInfo: [String:Any?]) {
        let vc = UIViewController.topMostController()
        if vc?.isKind(of: MainTabBarController.self) ?? false {
            NewsAction().go(from: vc!, news: userInfo)
            return
        }

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.openNews(userInfo: userInfo)
        }
    }
    
    // iOS 10 Support
    func jpushNotificationCenter(_ center: UNUserNotificationCenter?, willPresent notification: UNNotification?, withCompletionHandler completionHandler: @escaping (Int) -> Void) {
        // Required
        let userInfo = notification?.request.content.userInfo
        if (notification?.request.trigger is UNPushNotificationTrigger) {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue)) // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
    }

    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        // Required, iOS 7 Support
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)

//        let vc = M_NewsListVC()
//        UIViewController.topMostController()?.pushViewController(vc)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

        // Required, For systems with less than or equal to iOS 6
        JPUSHService.handleRemoteNotification(userInfo)
        
//        let vc = M_NewsListVC()
//        UIViewController.topMostController()?.pushViewController(vc)
    }




    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        let result = UMSocialManager.default()?.handleOpen(url)
        if !result! {
             // 其他如支付等SDK的回调
        }
        return result!
    }
    
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        if !(UMSocialManager.default()?.handleUniversalLink(userActivity, options: nil) ?? false) {
            // 其他SDK的回调
            
        }
        
        
        return true
    }
    
    func configUSharePlatforms() {
        UMSocialManager.default()?.setPlaform(.wechatSession, appKey: "wxef121ec5cc019059", appSecret: "8316c17bb6fb1d91e20a5b54bba451cf", redirectURL: "http://mobile.umeng.com/social")
        UMSocialManager.default()?.setLauchFrom(.wechatSession, completion: { (p1: Any?, p2:Error?) in
            print("setLauchFromPlatform:userInfoResponse:\(String(describing: p1))")
        })

    }
    
    func initjPushApns()  {
        let entity = JPUSHRegisterEntity()
        if #available(iOS 12.0, *) {
            entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.badge.rawValue | JPAuthorizationOptions.sound.rawValue | JPAuthorizationOptions.providesAppNotificationSettings.rawValue)
        } else {
             entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.badge.rawValue | JPAuthorizationOptions.sound.rawValue)
        }
        
//        if Double(UIDevice.current.systemVersion)! >= 8.0 {
            //可添加自定义 categories
//        }
        
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }
 
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        
        let result = UMSocialManager.default()?.handleOpen(url)
        if !result! {
                 // 其他如支付等SDK的回调
        }
        return result!

    }

    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        print("\(url),options:\(options)")

        print("url:\(String(describing: url.scheme)), host:\(String(describing: url.host)), path:\(url.path), query:\(String(describing: url.query?.urlqueryToDictionary()))")
        let result = UMSocialManager.default()?.handleOpen(url, options: options)
        if !result! {
             // 其他如支付等SDK的回调
        }
        return result!
    }
    
    // MARK: - Core Data stack app内数据库，暂时用不到

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "letuofu")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

//日志打印h扩展
import Foundation
import CocoaLumberjack

extension AppDelegate {
    func initLog(){
        dynamicLogLevel = Constant.LoggingLevel
        if dynamicLogLevel == .off {
            return
        }
        if !Constant.LoggingInConsoleMode{
            let consoleLogger = DDASLLogger.sharedInstance
            DDLog.add(consoleLogger!)
        }
        DDLog.add(DDASLLogger.sharedInstance)
        let fileLogger = DDFileLogger()
        fileLogger.maximumFileSize = 300 * 1024
        fileLogger.logFileManager.maximumNumberOfLogFiles = 7
        DDLog.add(fileLogger)
//        Constant.logFilePath = fileLogger.currentLogFileInfo.filePath
        Constant.fileLogger = fileLogger
        DDLogInfo(fileLogger.currentLogFileInfo.filePath)
    }
}
